package com.mysoft.gfyx.marketdevelop.service.impl;

import cn.hutool.core.codec.Base64;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.framework.service.AppService;
import com.mysoft.gfyx.marketdevelop.remoteService.RemoteProfitProvinceService;
import com.mysoft.gfyx.marketdevelop.remoteService.dto.GetProfitsResponse;
import com.mysoft.gfyx.marketdevelop.service.DMPService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.apache.commons.codec.digest.DigestUtils;

@Service
public class DMPServiceImp extends AppService implements DMPService {

    @Value("${dmp.DMP_HOST}")
    private String dmpHost;

    @Value("${dmp.DMP_SSO_LOGIN}")
    private String dmpSSOLogin;

    @Value("${dmp.tenant_code}")
    private String tenantCode;

    @Value("${dmp.secret}")
    private String secret;

    @Value("${dmp.account}")
    private String account;

    @Value("${dmp.tenant_token}")
    private String tenantToken;

    @Value("${dmp.page.test}")
    private String pageTest;

    @Value("${dmp.page.land}")
    private String pageLand;

    @Value("${dmp.page.project}")
    private String pageProject;

    @Value("${dmp.page.procurement}")
    private String pageProcurement;

    @Value("${dmp.page.work}")
    private String pageWork;

    @Value("${dmp.page.dashboard}")
    private String pageDashboard;

    @Value("${dmp.page.usage}")
    private String pageUsage;

    @Value("${dmp.page.user_application_board.market_report}")
    private String pageMarketReport;

    @Value("${dmp.page.user_application_board.clue_radar}")
    private String pageClueRadar;

    @Value("${dmp.page.market_monthly_report}")
    private String marketMonthlyReport;

    @Autowired
    private RemoteProfitProvinceService remoteProfitProvinceService;

    @Autowired
    private ContextManager contextManager;

    public String getLoginUrl(DMPPage page, MultiValueMap<String, String> query) {
        Date expTime = new Date();
        expTime.setTime(expTime.getTime() + 1000 * 36000);

        // 在url里统一加入供方营销的租户Code
        String gfyxSaasTenantCode = contextManager.fetchContextInfo().getTenantCode();
        if (!query.containsKey("tenant_code")) {
            query.add("tenant_code", gfyxSaasTenantCode);
        }
        if (!query.containsKey("tenant_token")) {
            query.add("tenant_token", DigestUtils.md5Hex(DigestUtils.md5Hex(gfyxSaasTenantCode) + tenantToken));
        }

        String redirectUri = UriComponentsBuilder.fromHttpUrl(getPageAddress(page)).queryParams(query).build().toString();
        String token = JWT.create()
                .withClaim("tenant_code", tenantCode)
                .withClaim("account", account)
                .withClaim("redirect", redirectUri)
                .withExpiresAt(expTime)
                .sign(Algorithm.HMAC256(secret));

        return getLoginUrlWithToken(token);
    }

    public HashMap<String, String> getLoginUrlV2() {
        HashMap<String, String> result = new HashMap<>();
        result.put("market_report", "");
        result.put("clue_radar", "");
        MultiValueMap<String, String> q = new LinkedMultiValueMap<>();
        GetProfitsResponse profits = remoteProfitProvinceService.getProfits();
        if (profits == null) {
            return result;
        }
        if (profits.isHasClueRadarProfit()) {
            result.put("clue_radar", this.getLoginUrl(DMPPage.ClueRadar, q));
        }
        if (profits.isHasMarketReportProfit()) {
            result.put("market_report", this.getLoginUrl(DMPPage.MarketReport, q));
        }

        return result;
    }

    protected String getPageAddress(DMPPage page) {
        String addr;
        switch (page) {
            case Land:
                addr = pageLand;
                break;
            case Project:
                addr = pageProject;
                break;
            case Procurement:
                addr = pageProcurement;
                break;
            case Work:
                addr = pageWork;
                break;
            case Dashboard:
                addr = pageDashboard;
                break;
            case Usage:
                addr = pageUsage;
                break;
            case MarketReport:
                addr = pageMarketReport;
                break;
            case ClueRadar:
                addr = pageClueRadar;
                break;
            case MarketMonthlyReport:
                addr = marketMonthlyReport;
                break;
            default:
                addr = pageTest;
        }

        return dmpHost + addr;
    }

    protected String getLoginUrlWithToken(String token) {
        return dmpSSOLogin + "?access_token=" + Base64.encode(token) + "&_from=gfyx";
    }
}
